package com.hbjycl.controller;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.ModelAndView;

import com.hbjycl.entity.Admin;
import com.hbjycl.service.AdminService;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Handles requests for the application home page.
 */
@Controller
public class DataController extends BaseController
{
    
    private static final Logger logger = LoggerFactory.getLogger(DataController.class);
    
    /**
     * 
     * 
     * @param session
     * @return
     */
    @RequestMapping(value = "/dataview", method = RequestMethod.GET)
    public ModelAndView dataview(HttpSession session, HttpServletRequest request)
    {  
    	ModelAndView mav = new ModelAndView();
    	if(session!=null)
    	{
            mav.addObject("user", session.getAttribute("student"));
    	}    
        mav.setViewName("data/datalist");
        return mav;
    }
    
    @RequestMapping(value = "/dataupload", method = RequestMethod.GET)
    public ModelAndView dataupload(HttpSession session, HttpServletRequest request)
    {  
    	ModelAndView mav = new ModelAndView();
    	if(session!=null)
    	{
            mav.addObject("user", session.getAttribute("student"));
    	}    
        mav.setViewName("data/dataupload");
        return mav;
    }
    
    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, HttpServletResponse response)
        throws IllegalStateException, IOException {
      // 创建一个通用的多部分解析器 ，用于解析SpringMVC的上下文
      CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request
          .getSession().getServletContext());
      // 解析request，判断是否为MultipartFile类型数据,即多部分请求
      if (multipartResolver.isMultipart(request)) {
        // 转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        // 取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
          // 取得上传文件
          MultipartFile file = multiRequest.getFile(iter.next());
          if (file != null) {
            // 取得当前上传文件的文件名称
            String myFileName = file.getOriginalFilename();
            // 如果名称不为“”,说明该文件存在，否则说明该文件不存在
            if (myFileName.trim() != "") {
              // 重命名上传后的文件名
              String fileName = new Date().getTime()
                  + file.getOriginalFilename();
              /*
               * //定义上传路径 String path = "H:/" + fileName; File
               * localFile = new File(path); //
               * 把文件拷贝到本地：transferTo（gest）将上传文件写到服务器指定文件上
               * file.transferTo(localFile);
               */

              // 如果用的是Tomcat服务器，则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\WEB-INF\\upload\\文件夹中
           /*   String realPath = request.getSession().getServletContext()
                  .getRealPath("/WEB-INF/upload");*/
              String realPath="d/upload";
              // 不必处理IO流关闭的问题，因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
              FileUtils.copyInputStreamToFile(file.getInputStream(), new File(
                  realPath, fileName));
            }
          }
        }
      }
      return "/data/datalist";
    }
}